import { CompanyInfo, CompanyList } from "@/api/enterprise";
import router from "@/router";
import { ElMessageBox } from "element-plus";
import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useCompanyDataStore = defineStore("companyData", () => {
  type companyModel = {
    address: string;
    area: number;
    area_id: number;
    avatar: string;
    birthday: string;
    capital: string;
    city_id: number;
    contact_address: string;
    create_time: string;
    enterprise_type: number;
    establish_time: string;
    id: number;
    industry_id: number;
    is_default: number;
    is_del: number;
    legal_person: string;
    legal_person_id: number;
    license: string;
    main_business: string;
    mobile: string;
    name: string;
    province_id: number;
    rolename: string;
    scale: string;
    social_credit_code: string;
    status: number;
    step: number;
    update_time: string;
    user_id: number;
    user_count: number;
    role_id: string;
    cu_id: number;
    is_enable: number;
    un_read: number;
  };

  const companyList = ref<companyModel[]>([]);
  const defaultCompany = computed<companyModel | undefined>(() => {
    return companyList.value.find((item) => item.is_default === 1);
  });
  const currentComanyInfo = ref<companyModel | null>(null);
  const createDialogVisible = ref(false);
  const joinDialogVisible = ref(false);
  const certifyCompany = ref<companyModel | null>(null);

  const init = async () => {
    await CompanyList().then((res) => {
      companyList.value = res.data;
      // getCompanyInfo()
    });
  };

  const setDefaultCompany = (company: companyModel | null) => {
    if (!company) return;
    companyList.value.forEach((item: companyModel) => {
      item.is_default = 0;
      if (item.cu_id == company.cu_id) {
        item.is_default = 1;
        getCompanyInfo();
      }
    });
  };

  const getCompanyInfo = async () => {
    if (defaultCompany.value && defaultCompany.value.is_enable == 1) {
      await CompanyInfo({
        id: defaultCompany.value!.cu_id,
      }).then((res) => {
        currentComanyInfo.value = res.data;
        localStorage.setItem("agent_id", res.data.agent_id);

        localStorage.setItem("company_id", res.data.id);

        const data1 = {
          aes_key: res.data.aes_key,
          token: res.data.token,
        };

        localStorage.setItem("aesinfo", JSON.stringify(data1));
        // localStorage.setItem("aes_key", res.data.aes_key);
        // localStorage.setItem("token", res.data.token);
      });
    }
  };

  const setCertifyCompany = (company: companyModel | null) => {
    certifyCompany.value = company;
  };

  const setMsgAllread = () => {
    const defaultCompany = companyList.value.find(
      (item) => item.is_default === 1
    );
    if (defaultCompany) {
      defaultCompany.un_read = 0;
    }
  };

  const checkAuth = (
    company: companyModel | null = defaultCompany.value || null
  ) => {
    if (company?.status !== 1) {
      ElMessageBox.confirm("当前企业还未认证，请前往认证", "提示", {
        confirmButtonText: "去认证",
        cancelButtonText: "稍后认证",
        type: "warning",
      })
        .then(async () => {
          try {
            if (!company) {
              throw new Error("company 是 undefined 或 null");
            }
            setCertifyCompany(company);
            await router.push("/myEnterprise/certify");
          } catch (error) {
            console.error("跳转失败:", error);
          }
        })
        .catch(() => {
          console.log("用户取消认证");
        });
      return false;
    }
    return true;
  };

  return {
    companyList,
    defaultCompany,
    currentComanyInfo,
    createDialogVisible,
    joinDialogVisible,
    certifyCompany,
    init,
    setDefaultCompany,
    getCompanyInfo,
    setCertifyCompany,
    setMsgAllread,
    checkAuth,
  };
});
